package com.nervenets.web.controller.handler.admin;

import com.nervenets.utils.JodaUtils;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.UserToken;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.hibernate.domain.user.UserRole;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletRequest;

public class AdminLoginHandler extends Handler<AdminLoginParams> {

    @Override
    public String handle(AdminLoginParams params, HttpServletRequest request) throws Exception {
        final User userByMobile = userDao.getUserByMobile(params.getMobile());
        if (null == userByMobile) return errorMessage(MessageCode.code_404, "账号不存在");
        if (!params.getPassword().equals(userByMobile.getPassword()))
            return errorMessage(MessageCode.code_444, "账号或密码有误");
        if (userByMobile.getDisable() > 0)
            return errorMessage(MessageCode.code_444, String.format("该账号已于%s被禁用", JodaUtils.timeLongToString(userByMobile.getDisable() * 1000L)));
        String tokenStr = new UserToken(userByMobile.getId(), 2).getTokenStr();
        globalVariablesService.setSession(userByMobile.getId(), Global.Constants.SESSION_USER_ROLE, userByMobile.getRole().toJSONString(), 0x5460);
        return successMessage(new Model(userByMobile.getId(), tokenStr, userByMobile.getInfo().getName(), userByMobile.getRole(), userByMobile.getMobile()));
    }

    @Override
    public String result() throws Exception {
        return successMessage(new Model());
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Model {
        private long id;
        private String token = "token";
        private String name = "名称";
        private UserRole role = new UserRole();
        private String mobile = "手机号码";
    }
}
